package br.com.vilababy.sigvb;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import br.com.vilababy.sigvb.constantes.SIGVBEnum;

public class SIGVBFactory {
	
	/**
	 * @author Diego Patrick da Silva Santos
	 */
	private static EntityManagerFactory emf;
	private static ThreadLocal<EntityManager> manager = new ThreadLocal<EntityManager>();

	static {
		System.out.println("Criando unidade de persistência");
		if (emf == null)
			criarBancoDados();
	}
	
	public static final void createEntityManager() {
		EntityManager em = emf.createEntityManager();
		manager.set(em);
	}
	
	public static final EntityManager getEM() {
		if (manager.get() == null || !manager.get().isOpen())
			manager.set(emf.createEntityManager());
		return manager.get();
	}
	
	public static final EntityManagerFactory getEmf() {
		return emf;
	}
	
	public static final void fecharEntityManager() {
		manager.get().close();
	}
	
	private static void criarBancoDados() {
		emf = Persistence.createEntityManagerFactory(SIGVBEnum.PERSISTENCE_UNIT.getValor());
	}
	
}
